<template>
  <div class="addGoods">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
      <el-steps
        :active="activeIndex - 0"
        finish-status="success"
        style="margin-top: 20px; font-size: 10px"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-position="top"
      >
        <!-- //tabs标签页 -->
        <el-tabs
          tab-position="left"
          style="margin-top: 20px"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="changeTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type='number' v-model.number="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" >
              <el-input v-model.number="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="ruleForm.goods_number"></el-input>
            </el-form-item>

            <!-- 级联选择器 -->
            <el-form-item label="商品类型" prop="goods_cat">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="cascaderData"
                :props="cascaderPropsConfig"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 动态参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(checkbox) in checkboxData"
              :key="checkbox.attr_id"
            >
              <h4>{{ checkbox.attr_name }}</h4>
              <el-checkbox-group
                v-model="checkbox.attr_vals"
                size="mini"
                @change="checkboxEvent"
              >
                <el-checkbox
                  :label="item"
                  v-for="item in checkbox.attr_vals"
                  :key="item"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态参数 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in staticData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              :action="action"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersAuthorization"
              :on-success="onSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="ruleForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="magin-top: 20px" @click="addGoods"
              >添加</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="dialogVisible" title="图片预览 " width="50%">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0', //步骤条
      inputValue: '', //级联绑定value
      cascaderData: [],
      goods_id:'',
      ruleForm: {
        // attr_vals: [], //绑定级联选择器
        // vals: '', //v-model  级联选择
        goods_name: '',  //1 
        goods_cat: [], //用  ，  分割  2
        goods_price: 0, //3
        goods_number: 0, //4
        goods_weight: 0,  //5
        goods_introduce: '',  //6
        pics: [], //7
        attrs: [], //8
      },
      rules: {
        goods_name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请填写价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请填写重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请填写数量', trigger: 'blur' }],
        goods_introduce: [
          { required: true, message: '请填写', trigger: 'blur' },
        ],
        goods_cat: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      cascaderPropsConfig: {
        //级联配置
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      checkboxGroup: [], //收集
      checkboxData: [], //多选框循环数据  动态   显示
      staticData: [], //显示
      collectStaticData: {},

      action: 'http://127.0.0.1:8888/api/private/v1/api/', //图片上传地址
      // fileList: [],
      headersAuthorization: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      dialogImageUrl: '',
      dialogVisible: false,
    }
  },
  created() {
    this.getCascaderData()
  },
  methods: {
    async getCascaderData() {
      const { meta, data } = await this.$axios.get('/api/categories')
      if (meta.status == 200) {
        this.cascaderData = data
        // console.log(data)
      }
    },
    handleChange(value) {
      //级联触发
      if (value.length != 3) {
        this.ruleForm.goods_cat = []
      }
      this.goods_id = value.slice(-1)
      console.log(this.ruleForm.goods_cat, value)
    },
    beforeLeave(after, before) {
      const { goods_name, goods_cat } = this.ruleForm
      if (before == 0 && goods_cat.length != 3 && !goods_name.trim()) {
        this.$message.error('请填写完整')
        return false
      }
    },
    async changeTabs(tag) {
      //tabs切换成功触发的函数
      

      if (tag.index == 1) {
        const { meta, data } = await this.$axios.get(
          `/api/categories/${this.goods_id}/attributes`,
          { params: { sel: 'many' } }
        )
        if (meta.status == 200) {
          data.forEach((item,index)=>{
            data[index].attr_vals=item.attr_vals.split(' ')
          })
          this.checkboxData = data

          // console.log('动态');
          // console.log(data);
        }
      } else if (tag.index == 2) {
        const { meta, data } = await this.$axios.get(
          `/api/categories/${this.goods_id}/attributes`,
          { params: { sel: 'only' } }
        )
        if (meta.status == 200) {
          this.staticData = data
          // console.log('静态');
          // console.log(data)
        }
      }
    },
    checkboxEvent() {
      //多选框
      console.log(this.checkboxGroup)
    },
    // 图片操作
    handleRemove(file) {
     this.ruleForm.pics.forEach((item,index)=>{
       if(item.url==file.url){
         this.ruleForm.pics.splice(index,1)
       }
     })
      // console.log(file, fileList)
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
     onSuccess(res, file) {
      
      this.ruleForm.pics.push({name:file.name,url:file.url})
    },
    //最后添加图片
    addGoods() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const goods_cat=this.ruleForm.goods_cat.join(',')
          var result=Object.assign({},this.ruleForm)
          result.goods_cat=goods_cat
          result.attrs=[...this.checkboxData,...this.staticData]
          // this.ruleForm.attrs=[]

           const {meta,data}= await this.$axios.post('/api/goods',{...result})
           if(meta.status==201){
             this.$message.success('添加成功')
              this.$router.replace('/home/goods')
             console.log(data);
           }else{
             console.log(meta);
             this.$message.error('添加失败')
             console.log(data);
           }
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-input {
  width: 300px;
}
.el-checkbox {
  margin: 5px 10px 5px 0 !important;
}
</style>
